package com.ruoyi.channelApi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.channel.domain.ChannelMsgSent;
import com.ruoyi.channel.domain.TChannelDataConf;
import com.ruoyi.channel.mapper.TChannelDataConfMapper;
import com.ruoyi.channel.service.ChannelDisService;
import com.ruoyi.channelApi.domain.CfCrmRequest;
import com.ruoyi.channelApi.domain.ChannelRequest;
import com.ruoyi.channelApi.domain.ChannelVisit;
import com.ruoyi.channelApi.domain.TChannelPush;
import com.ruoyi.channelApi.domain.TelRequest;
import com.ruoyi.channelApi.domain.bo.TChannelPushBo;
import com.ruoyi.channelApi.mapper.TChannelPushMapper;
import com.ruoyi.channelApi.service.ChannelApiService;
import com.ruoyi.channelApi.service.ITChannelPushService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.customer.domain.CustomerSource;
import com.ruoyi.enums.ChannelPushEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RequiredArgsConstructor
@Service
@Slf4j
public class ChannelApiServiceImpl implements ChannelApiService {

    private final TChannelPushMapper channelPushMapper;
    private final ITChannelPushService channelPushService;
    private final TChannelDataConfMapper dataConfMapper;
    private final ChannelDisService channelDisService;

    @Override
    @Transactional
    public Map<String, Object> saveChannelPushCrm(ChannelRequest channelRequest) {
        ChannelVisit channelVisit = new ChannelVisit();
        channelRequest.setChannelSource(ChannelPushEnum.CRM_CHANNEL.getValue());
        channelVisit.setParamInfo(JsonUtils.toJsonString(channelRequest));
        channelVisit.setChannelSource(ChannelPushEnum.CRM_CHANNEL.getValue());
        channelVisit.setChannelPort(ChannelPushEnum.of(ChannelPushEnum.CRM_CHANNEL.getValue(), "saveChannelPushCrm"));
        Map<String, Object> map = new HashMap<>(1 << 4);
        // 待添加信息 处理人员信息
        LambdaQueryWrapper<TChannelDataConf> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TChannelDataConf::getChannelSource, ChannelPushEnum.CRM_CHANNEL.getValue());
        TChannelDataConf dataConf = dataConfMapper.selectOne(lambdaQueryWrapper);

        // 未开启 不接收数据了
        if (dataConf == null || Objects.equals("0", dataConf.getIsOpen())) {
            map.put("code", 201);
            map.put("msg", "fail");
            map.put("fail-msg", "未开启");
            channelVisit.setResultInfo(JsonUtils.toJsonString(map));
            channelPushRecord(channelVisit);
            return map;
        }

        // 参数没有传递
        if (channelRequest == null) {
            map.put("code", 201);
            map.put("msg", "fail");
            map.put("fail-msg", "参数没有传递");
            channelVisit.setResultInfo(JsonUtils.toJsonString(map));
            channelPushRecord(channelVisit);
            return map;
        } else {
            // 手机号为空
            if (!StringUtils.isNotBlank(channelRequest.getTel())) {
                map.put("code", 201);
                map.put("msg", "fail");
                map.put("fail-msg", "手机号为空");
                channelVisit.setResultInfo(JsonUtils.toJsonString(map));
                channelPushRecord(channelVisit);
                return map;
            }
        }
        // 去除前后空格-手机号
        channelRequest.setTel(channelRequest.getTel().trim());
        LambdaQueryWrapper<TChannelPush> pushlambdaQueryWrapper = new LambdaQueryWrapper<>();
        pushlambdaQueryWrapper.eq(TChannelPush::getChannelSource, ChannelPushEnum.CRM_CHANNEL.getValue());
        pushlambdaQueryWrapper.eq(TChannelPush::getPhoneMd5, DigestUtils.md5Hex(channelRequest.getTel()));
        Long count = channelPushMapper.selectCount(pushlambdaQueryWrapper);
        if (count > 0) {
            map.put("code", 201);
            map.put("msg", "fail");
            map.put("fail-msg", "撞库");
            channelVisit.setResultInfo(JsonUtils.toJsonString(map));
            channelPushRecord(channelVisit);
            return map;
        }
        // 保存推送信息
        TChannelPushBo pushBo = new TChannelPushBo();
        try {
            channelRequest.setSource("通融字节");
            pushBo.setChannelSource(ChannelPushEnum.CRM_CHANNEL.getValue());
            pushBo.setPushTime(DateUtils.getNowDate());
            pushBo.setTel(channelRequest.getTel());
            pushBo.setDataInfo(JsonUtils.toJsonString(channelRequest));
            pushBo.setPhoneMd5(DigestUtils.md5Hex(channelRequest.getTel()));
            channelPushService.insertByBo(pushBo);
            map.put("code", 200);
            map.put("msg", "success");
            // 开始分配
            Map<String, String> resultInfo = channelDisService.backChannelCustomerInfo(pushBo.getId());
            channelVisit.setResultInfo(JsonUtils.toJsonString(map));
            channelPushRecord(channelVisit);
            String flag = resultInfo.get("flag");
            // 发送消息
            String sentType = resultInfo.get("sentType");
            if (Objects.equals(flag, "0")) {
                if (Objects.equals(sentType, "bus")) {
                    String sentInfo = resultInfo.get("sentInfo");
                    ChannelMsgSent channelMsgSent = JsonUtils.parseObject(sentInfo, ChannelMsgSent.class);
                    channelDisService.sentToBusMsg(channelMsgSent);
                }
            } else if (Objects.equals(flag, "6")) {
                  if (Objects.equals(sentType, "admin")) {
                    String sentInfo = resultInfo.get("sentInfo");
                    ChannelMsgSent channelMsgSent = JsonUtils.parseObject(sentInfo, ChannelMsgSent.class);
                    channelDisService.sentToAdminMsg(channelMsgSent);
                }
            }
            // 更新一下人员信息
            channelDisService.channelDisUserId(dataConf.getId());

            // 更新来源信息
            if (StringUtils.isNotBlank(channelRequest.getSource())) {
                updateCustomerSource(channelRequest.getTel(), channelRequest.getSource(), dataConf.getChannelName());
            }

            return map;
        } catch (Exception e) {
            log.info("推送客户失败：{}", JsonUtils.toJsonString(channelRequest));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("code", 201);
            map.put("msg", "fail-保存信息异常");
            map.put("fail-msg", e.getMessage());
            channelVisit.setResultInfo(JsonUtils.toJsonString(map));
            channelPushRecord(channelVisit);
            return map;
        }
    }

    private void updateCustomerSource(String tel, String source, String createBy) {
        CustomerSource customerSource = new CustomerSource();
        customerSource.setSource(source);
        customerSource.setCreateBy(createBy);
        customerSource.setTel(tel);
        SpringUtils.context().publishEvent(customerSource);
    }


    @Override
    public Map<String, Object> telCheck(TelRequest telRequest) {
        ChannelVisit channelVisit = new ChannelVisit();
        channelVisit.setParamInfo(JsonUtils.toJsonString(telRequest));
        channelVisit.setChannelSource(ChannelPushEnum.CRM_CHANNEL.getValue());
        channelVisit.setChannelPort(ChannelPushEnum.of(ChannelPushEnum.CRM_CHANNEL.getValue(), "telCheck"));
        Map<String, Object> map = new HashMap<>(1 << 4);
        if (telRequest == null) {
            map.put("code", 201);
            map.put("status", "false");
            map.put("fail-msg", "参数缺失");
            channelVisit.setResultInfo(JsonUtils.toJsonString(map));
            channelPushRecord(channelVisit);
            return map;
        } else {
            if (!StringUtils.isNotBlank(telRequest.getPhoneMd5())) {
                map.put("code", 201);
                map.put("status", "false");
                map.put("fail-msg", "手机号为空");
                channelVisit.setResultInfo(JsonUtils.toJsonString(map));
                channelPushRecord(channelVisit);
                return map;
            }
        }
        LambdaQueryWrapper<TChannelPush> pushlambdaQueryWrapper = new LambdaQueryWrapper<>();
        pushlambdaQueryWrapper.eq(TChannelPush::getPhoneMd5, telRequest.getPhoneMd5());
        pushlambdaQueryWrapper.eq(TChannelPush::getChannelSource, ChannelPushEnum.CRM_CHANNEL.getValue());
        Long count = channelPushMapper.selectCount(pushlambdaQueryWrapper);
        if (count > 0) {
            map.put("code", 201);
            map.put("status", "false");
            map.put("fail-msg", "撞库");
            channelVisit.setResultInfo(JsonUtils.toJsonString(map));
            channelPushRecord(channelVisit);
            return map;
        }
        map.put("code", 200);
        map.put("status", "true");
        channelVisit.setResultInfo(JsonUtils.toJsonString(map));
        channelPushRecord(channelVisit);
        return map;
    }


    private void channelPushRecord(ChannelVisit channelVisit) {
        SpringUtils.context().publishEvent(channelVisit);
    }


    @Async
    @EventListener
    public void saveChannelPushRecord(ChannelVisit channelVisit) {
        channelPushMapper.insertChannelVisit(channelVisit);
    }

    @Override
    @Transactional
    public Map<String, Object> cfCrm(CfCrmRequest crmRequest) {
        ChannelVisit channelVisit = new ChannelVisit();
        channelVisit.setParamInfo(JsonUtils.toJsonString(crmRequest));
        channelVisit.setChannelSource(ChannelPushEnum.CF_CRM_CHANNEL.getValue());
        channelVisit.setChannelPort(ChannelPushEnum.of(ChannelPushEnum.CF_CRM_CHANNEL.getValue(), "cfCrm"));
        Map<String, Object> map = new HashMap<>(1 << 4);

        // 待添加信息 处理人员信息
        LambdaQueryWrapper<TChannelDataConf> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(TChannelDataConf::getChannelSource, ChannelPushEnum.CF_CRM_CHANNEL.getValue());
        TChannelDataConf dataConf = dataConfMapper.selectOne(lambdaQueryWrapper);

        // 未开启 不接收数据了
        if (dataConf == null || Objects.equals("0", dataConf.getIsOpen())) {
            map.put("code", 201);
            map.put("msg", "fail");
            map.put("fail-msg", "未开启");
            channelVisit.setResultInfo(JsonUtils.toJsonString(map));
            channelPushRecord(channelVisit);
            return map;
        }

        // 参数没有传递
        if (crmRequest == null) {
            map.put("code", 201);
            map.put("msg", "fail");
            map.put("fail-msg", "参数没有传递");
            channelVisit.setResultInfo(JsonUtils.toJsonString(map));
            channelPushRecord(channelVisit);
            return map;
        } else {
            // 手机号为空
            if (!StringUtils.isNotBlank(crmRequest.getMobile())) {
                map.put("code", 201);
                map.put("msg", "fail");
                map.put("fail-msg", "手机号为空");
                channelVisit.setResultInfo(JsonUtils.toJsonString(map));
                channelPushRecord(channelVisit);
                return map;
            }
        }
        // 去除前后空格-手机号
        crmRequest.setMobile(crmRequest.getMobile().trim());
        LambdaQueryWrapper<TChannelPush> pushlambdaQueryWrapper = new LambdaQueryWrapper<>();
        pushlambdaQueryWrapper.eq(TChannelPush::getTel, crmRequest.getMobile());
        pushlambdaQueryWrapper.eq(TChannelPush::getChannelSource, ChannelPushEnum.CF_CRM_CHANNEL.getValue());
        Long count = channelPushMapper.selectCount(pushlambdaQueryWrapper);
        if (count > 0) {
            map.put("code", 201);
            map.put("status", "false");
            map.put("fail-msg", "重复推送");
            channelVisit.setResultInfo(JsonUtils.toJsonString(map));
            channelPushRecord(channelVisit);
            return map;
        }
        // 保存推送信息
        TChannelPushBo pushBo = new TChannelPushBo();
        try {
            pushBo.setChannelSource(ChannelPushEnum.CF_CRM_CHANNEL.getValue());
            pushBo.setPushTime(DateUtils.getNowDate());
            pushBo.setTel(crmRequest.getMobile());
            pushBo.setDataInfo(JsonUtils.toJsonString(crmRequest));
            pushBo.setPhoneMd5(DigestUtils.md5Hex(crmRequest.getMobile()));
            channelPushService.insertByBo(pushBo);
            map.put("code", 200);
            map.put("msg", "success");
            // 开始分配
            Map<String, String> resultInfo = channelDisService.backChannelCustomerInfo(pushBo.getId());
            channelVisit.setResultInfo(JsonUtils.toJsonString(map));
            channelPushRecord(channelVisit);
            String flag = resultInfo.get("flag");
            // 发送消息
            String sentType = resultInfo.get("sentType");
            if (Objects.equals(flag, "0")) {
                if (Objects.equals(sentType, "bus")) {
                    String sentInfo = resultInfo.get("sentInfo");
                    ChannelMsgSent channelMsgSent = JsonUtils.parseObject(sentInfo, ChannelMsgSent.class);
                    channelDisService.sentToBusMsg(channelMsgSent);
                }
            }  else if (Objects.equals(flag, "6")) {
                if (Objects.equals(sentType, "admin")) {
                    String sentInfo = resultInfo.get("sentInfo");
                    ChannelMsgSent channelMsgSent = JsonUtils.parseObject(sentInfo, ChannelMsgSent.class);
                    channelDisService.sentToAdminMsg(channelMsgSent);
                }
            }
            // 更新一下人员信息
            channelDisService.channelDisUserId(dataConf.getId());

            // 更新来源信息
            if (StringUtils.isNotBlank(crmRequest.getSource())) {
                updateCustomerSource(crmRequest.getMobile(), crmRequest.getSource(), dataConf.getChannelName());
            }
            return map;
        } catch (Exception e) {
            log.info("推送客户失败：{}", JsonUtils.toJsonString(crmRequest));
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            map.put("code", 201);
            map.put("msg", "fail-保存信息异常");
            map.put("fail-msg", e.getMessage());
            channelVisit.setResultInfo(JsonUtils.toJsonString(map));
            channelPushRecord(channelVisit);
            return map;
        }
    }



}
